package com.tutu.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UnicodeUtil {

    /**
     * 编码
     */
    public static String unicodeEncode(String string) {
        if (BaseUtil.isBlank(string)) return "";

        char[] utfBytes = string.toCharArray();
        StringBuilder unicodeBytes = new StringBuilder();

        for (char utfByte : utfBytes) {
            String hexB = Integer.toHexString(utfByte);

            if (hexB.length() <= 2) hexB = "00" + hexB;

            unicodeBytes.append("\\u").append(hexB);
        }

        return unicodeBytes.toString();
    }

    /**
     * 解码
     */
    public static String unicodeDecode(String string) {
        if (BaseUtil.isBlank(string)) return "";

        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
        Matcher matcher = pattern.matcher(string);
        char ch;

        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            string = string.replace(matcher.group(1), ch + "");
        }

        return string;
    }
}
